package me.yxy.mobanddd.domain.transportorder;

import com.google.common.collect.Iterables;
import me.yxy.mobanddd.controller.request.command.AddTransportRequest;
import me.yxy.mobanddd.domain.warehouse.Warehouse;
import me.yxy.mobanddd.domain.warehouse.WarehouseRepository;
import me.yxy.mobanddd.exception.BusinessException;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.transaction.Transactional;
import java.util.Date;
import java.util.Optional;
import java.util.Random;

/**
 * 调度单工厂，负责创建调度单
 */
@Component
@Transactional
public class TransportOrderFactory {


    @Autowired
    private TransportOrderRepository transportOrderRepository;

    /**
     * Factory作为一种特殊的Command，其中允许出现其他所需要的repository
     */
    @Autowired
    private WarehouseRepository warehouseRepository;

    /**
     * 根据标准的创建运单请求报文来创建
     * @param request
     * @return
     */
    public TransportOrder createByRequest(AddTransportRequest request) {
        TransportOrder transportOrder = new TransportOrder();

        transportOrder.setCreatedTime(new Date());
        transportOrder.setType(request.getType());
        transportOrder.setCode(getValidCode(request.getCode()));
        transportOrder.setReceiverName(request.getReceiverName());
        transportOrder.setReceiverLocation(request.getReceiverLocation());
        transportOrder.setReceiverTel(request.getReceiverTel());
        transportOrder.setStatus(TransportOrderStatus.INIT);
        buildCoordinatate(transportOrder,request.getReceiverLocation());

        //仓库处理
        handlerWarehouse(transportOrder,request.getWarehouseId());


        transportOrderRepository.save(transportOrder);
        return transportOrder;
    }

    private void handlerWarehouse(TransportOrder transportOrderDto, Long warehouseId) {

        //如果没有传入仓库参数，则通过业务逻辑来指定一个仓库
        if(warehouseId==null){
            Iterable<Warehouse> allWarehouses = warehouseRepository.findAll();
            int idx = new Random().nextInt(Iterables.size(allWarehouses));
            transportOrderDto.setWarehouse(Iterables.get(allWarehouses,idx));
            return;
        }

        Optional<Warehouse> warehouse = warehouseRepository.findById(warehouseId);
        if(warehouse.isPresent()){
            transportOrderDto.setWarehouse(warehouse.get());
        }else{
            throw new BusinessException("没有找到指定的仓库");
        }
    }

    /**
     * 根据地址解析，这里就随便玩玩了
     * @param transportOrderDto
     * @param receiverLocation
     */
    private void buildCoordinatate(TransportOrder transportOrderDto, String receiverLocation) {

        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
        }

        int seed = receiverLocation.length();
        Random random = new Random(seed);
        transportOrderDto.setReceiveLatitude(31.0 + random.nextDouble());
        transportOrderDto.setReceiveLongitude(121.0 + random.nextDouble());
    }

    private String getValidCode(String code) {
        if(StringUtils.isEmpty(code)){
            code = DateTime.now().toString("yyyyMMddHHmmss")+new Random().nextInt(1000);
            return code;
        }else{
            Optional<TransportOrder> existWithCode = transportOrderRepository.findByCode(code);
            if(!existWithCode.isPresent()){
                return code;
            }else{
                throw new BusinessException("运输单号["+code+"]已存在");
            }
        }
    }
}
